#include "ASIO.h"
#include "..\base\ASStdLib.h"
#include "ASLogic.h"

static ASINT s_record_handle;
static ASINT s_sys_hanlde;

ASBOOL as_io_init(void)
{
    if (mrc_fileState(IKAMA_DIR) != MR_IS_DIR)
    {
        mrc_mkDir(IKAMA_DIR);
    }

    if ((s_record_handle = mrc_open(IKAMA_RECORD_FILE, MR_FILE_CREATE | MR_FILE_RDWR)) == ASNULL)
        return ASFALSE;

    if ((s_sys_hanlde = mrc_open(IKAMA_SYS_FILE, MR_FILE_CREATE | MR_FILE_RDWR)) == ASNULL)
        return ASFALSE;

    return ASTRUE;
}

ASBOOL as_io_deinit(void)
{
    if (s_record_handle != ASNULL)
        mrc_close(s_record_handle);

    if (s_sys_hanlde != ASNULL)
        mrc_close(s_sys_hanlde);

    return ASTRUE;
}

ASBOOL as_io_write_record(ASINT type, void* record_p, ASINT record_size)
{
    ASBOOL ret = ASTRUE;

    if (s_record_handle != ASNULL)
    {
        ret = mrc_seek(s_record_handle, type * record_size, MR_SEEK_SET);

        if (ret == MR_FAILED)
            return ASFALSE;

        ret = mrc_write(s_record_handle, record_p, record_size);

        if (ret == MR_FAILED)
            return ASFALSE;

        return ASTRUE;
    }
    else
        return ASFALSE;
}

ASBOOL as_io_read_record(ASINT type, void* record_p, ASINT record_size)
{
    ASBOOL ret = ASTRUE;

    if (s_record_handle != ASNULL)
    {
        ret = mrc_seek(s_record_handle, type * record_size, MR_SEEK_SET);

        if (ret == MR_FAILED)
            return ASFALSE;

        ret = mrc_read(s_record_handle, record_p, record_size);

        if(ret == MR_FAILED)
            return ASFALSE;

        return ASTRUE;
    }
    else
        return ASFALSE;
}

ASBOOL as_io_write_sysinfo(void* sysinfo, ASINT sysinfo_size)
{
    ASBOOL ret = ASTRUE;

    if (s_sys_hanlde != ASNULL)
    {
        ret = mrc_write(s_sys_hanlde, sysinfo, sysinfo_size);

        if (ret == MR_FAILED)
            return ASFALSE;

        return ASTRUE;
    }
    else
        return ASFALSE;
}

ASBOOL as_io_read_sysinof(void* sysinfo, ASINT sysinfo_size)
{
    ASBOOL ret = ASTRUE;

    if (s_sys_hanlde != ASNULL)
    {
        ret = mrc_read(s_sys_hanlde, sysinfo, sysinfo_size);

        if(ret == MR_FAILED)
            return ASFALSE;

        return ASTRUE;
    }
    else
        return ASFALSE;
}